/*
 * utils.cpp -- Methods usefull to other classes
 *
 * Copyright (C) 2010 Andrea Grandi
 * Authors: Andrea Grandi <a.grandi@gmail.com>
 *
 * This file is part of LastGo and is published under the GNU GPLv2
 * See the README file for more details.
 */

#include "utils.h"

Utils::Utils(QObject *parent) :
    QObject(parent)
{
}

/* Generates the md5 hash of a string. */

QString Utils::md5Signature(const QString value)
{
    QByteArray hash = QCryptographicHash::hash(value.toUtf8(), QCryptographicHash::Md5);
    QString signature(hash.toHex());
    return signature;
}

/* Takes all parameters (keys and values) that are ordered alphabetically (due to a QMap feature)
   and concatenate them all together. At the end it appends the secret string. */

QString Utils::buildSignature(const QMap<QString, QString> params, const QString secret)
{
    QString signature = "";
    QMapIterator<QString, QString> i(params);

    while (i.hasNext())
    {
         i.next();
         signature.append(i.key());
         signature.append(i.value());
    }

    signature.append(secret);
    return this->md5Signature(signature);
}

/* Generates an authentication token for mobile authentication.
   The following formula is used: md5(username + md5(password)) */

QString Utils::getAuthToken(const QString username, const QString password)
{
    QString md5pass = this->md5Signature(password);
    QString usermd5pass = username + md5pass;
    return this->md5Signature(usermd5pass);
}

/* Generates an URL for the current API request */

QString Utils::buildApiUrl(const QString baseurl, const QMap<QString, QString> params)
{
    QString url = "";

    url.append(baseurl);
    url.append("?");
    url.append("method=" + params["method"]);

    QMapIterator<QString, QString> i(params);

    while (i.hasNext())
    {
         i.next();

         if(i.key() != "method")
            url.append("&" + i.key() + "=" + i.value().toUtf8());
    }

    return url;
}

/* Create a QByteArray containing all parameters needed for a HTTP POST request */

QByteArray Utils::buildPostParameters(const QMap<QString, QString> params)
{
    QByteArray post_params;
    QMapIterator<QString, QString> i(params);

    while (i.hasNext())
    {
         i.next();

         if(post_params.length() > 0)
            post_params.append("&" + i.key() + "=" + i.value().toUtf8());
         else
            post_params.append(i.key() + "=" + i.value().toUtf8());
    }

    return post_params;
}

/* Create a Scrobbling Authentication Token.
   The following formula is used: token = md5(shared_secret + timestamp) */

QString Utils::getScrobblerAuthToken(QString api_secret, QString timestamp)
{
    QString api_stamp = api_secret + timestamp;
    QByteArray hash = QCryptographicHash::hash(api_stamp.toUtf8(), QCryptographicHash::Md5);
    return hash.toHex();
}
